package com.itlangzi.mybatis.factory;

import com.itlangzi.mybatis.page.Pagination;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;

public class PaginationWrapperFactory extends DefaultObjectWrapperFactory {

    @Override
    public boolean hasWrapperFor(Object object) {
        if (object instanceof Pagination) {
            return true;
        }
        return super.hasWrapperFor(object);
    }

    @Override
    public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
        if (object instanceof Pagination) {
            // 使用自定义对象包装
            Pagination target = (Pagination) object;
            setPaginationProperties(target);
            return new PaginationWrapper(target);
        }
        return super.getWrapperFor(metaObject, object);
    }

    /**
     * 拷贝分页的信息
     *
     * @param target 目标分页对象
     */
    private void setPaginationProperties(Pagination target) {
        Pagination pagination = PaginationHelper.getPagination();
        if (pagination != null) {
            target.setPage(pagination.getPage());
            target.setSize(pagination.getSize());
            target.setTotalElements(pagination.getTotalElements());
        }
        PaginationHelper.clear();
    }
}
